/**
 * 
 */
package com.roc.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.roc.dao.DaoException;
import com.roc.dao.ISQLBaseDao;
import com.roc.dao.IUserDao;
import com.roc.exception.UserException;
import com.roc.newPage.IPageDao;
import com.roc.pojo.LoginIpJnls;
import com.roc.pojo.MerchantModuleRight;
import com.roc.pojo.MessageSend;
import com.roc.pojo.Operators;
import com.roc.pojo.TblDictionaryLayerItem;
import com.roc.pojo.TblMchtInf;
import com.roc.pojo.User;
import com.roc.service.IUserService;
import com.roc.service.ServiceException;
import com.roc.util.Constance;
import com.roc.util.IDGenerator;
import com.roc.util.MD5Utils;
import com.roc.util.Utils;
import com.roc.util.constant.DateFormat;
import com.roc.util.constant.MerinfoModule;
import com.roc.util.constant.OperatorsStatus;
import com.roc.util.constant.Role;

/**
 * @author RenPengFei
 * 
 *         2011-11-22
 */
@Service
public class UserServiceImpl implements IUserService {

	Logger logger = LogManager.getLogger(UserServiceImpl.class);

	@Autowired
	private IUserDao userDao;
	
	@Autowired
	private IPageDao  pageDao;
	
	@Autowired
	private ISQLBaseDao sqlBaseDao;
	/*
	 * (non-Javadoc)
	 * 
	 * @see com.tit.service.UserService#userLogin(java.lang.String,
	 * java.lang.String)
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public User userLogin(String userId, String password) throws UserException {
		User user = null;
		try {
			user = userDao.findUserById(userId);
		} catch (DaoException e) {
			logger.error(e.getMessage(), e);
			throw new UserException(e.getMessage());
		}
		if (user == null) {
			logger.debug("用户[" + userId + "]不存在");
			throw new UserException("用户[" + userId + "]不存在");
		}
		
		try {
			if (!Utils.isBlank(password)) {
				logger.debug("密码加密");
				password = MD5Utils.MD5Encode(password);
			} else {
				logger.debug("输入密码为空");
				password = "";
			}
			if (!password.equals(user.getUserPwd())) {
				logger.debug("输入密码[" + password + "] 用户密码[" + user.getUserPwd()
						+ "]");
				throw new UserException("用户[" + userId + "]密码错误");
			}
			user.setLastDate(new Date());
			userDao.updateUser(user);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new UserException(e.getMessage());
		}

		return user;
	}

	@Transactional(propagation = Propagation.REQUIRED)
	public void addUser(User user) throws UserException {
		try {
			user.setUserId(IDGenerator.get18ID());
			userDao.addUser(user);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new UserException("新增用户失败");
		}
	}

	@Transactional(propagation = Propagation.REQUIRED)
	public void deleteUser(User user) throws UserException {
		try {
			userDao.deleteUser(user);
		} catch (DaoException e) {
			logger.error(e.getMessage(), e);
			throw new UserException("删除用户失败");
		}
	}

	@Transactional(propagation = Propagation.REQUIRED)
	public void updateUser(User user) throws UserException {
		try {
			userDao.updateUser(user);
		} catch (DaoException e) {
			logger.error(e.getMessage(), e);
			throw new UserException("用户更新失败");
		}
	}

	@Transactional(propagation = Propagation.REQUIRED)
	public boolean addOperForMerinfo(TblMchtInf  merinfo,Operators currentOper) throws ServiceException {
		// 添加操作员
				try {
					Operators ops = new Operators();
					ops.setAccountNo(merinfo.getId());
					ops.setRealName(merinfo.getNameBusi());
					String pwd = MD5Utils.MD5Encode(merinfo.getContactPhoneNo().substring(5));
					ops.setPwd(pwd);
					DateFormat df = DateFormat.ZH_DEL_ALL;
					Date newDate = df.toDate(Constance.formateDateTime());
					newDate.setYear(newDate.getYear() + 1);
					ops.setValidEndDate(df.toString(newDate));// 操作员有效期
					ops.setValidStartDate(Constance.formateDateTime());// 有效期开始日期
					ops.setMobile(merinfo.getContactPhoneNo());// 法人手机号
					ops.setOrgCode(currentOper.getOrgCode());// 机构
					ops.setStatus(OperatorsStatus.OK.getCode());// 状态
					if(currentOper.getRoleType().equals(Role.AGENT_BUSS.getCode())){//如果是业务员则添加业务员上级=代理商
						ops.setSuperiorId(currentOper.getSuperiorId());// 父类id
					}else{
						ops.setSuperiorId(currentOper.getId());// 父类id
					}
					
					ops.setOperators(merinfo.getId());// op
					ops.setRoleType(Role.MERCHANT.getCode());// 角色类别
					ops.setFlag("0");
					String time = "";
					Date dt = new Date();
					SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
					time = sdf.format(dt);
					ops.setUpdatePWD(time);
					// ops.setRealName(mer.getMerName());
					ops.setSex("1");
					userDao.editSave(ops);
					// 添加商户权限（初始6个权限）
					for (int i = 0; i < 6; i++) {
						MerchantModuleRight mmr = new MerchantModuleRight();
						mmr.setMerchantNo(merinfo.getId());
						mmr.setOperators(currentOper.getAccountNo());
						if (i == 0) {
							mmr.setModuleCode(MerinfoModule.C_02_M_02.getName());// 商户查询
						} else if (i == 1) {
							mmr.setModuleCode(MerinfoModule.C_04_M_01.getName());// 交易查询
						} else if (i == 2) {
							mmr.setModuleCode(MerinfoModule.C_04_M_02.getName());// 结算查询
						} else if (i == 3) {
							mmr.setModuleCode(MerinfoModule.C_07_M_02.getName());// 终端查询
						} else if (i == 4) {
							mmr.setModuleCode(MerinfoModule.C_04_M_10.getName());// 代付查询
						} else if (i == 5) {
							mmr.setModuleCode(MerinfoModule.C_04_M_11.getName());// 清算查询
						}
						userDao.editSave(mmr);
					}
				} catch (Exception e) {
					e.printStackTrace();
					logger.error("######商户操作员添加失败######", e);
					throw new ServiceException("商户操作员添加失败");
				}
				return false;
	}
 
	@Transactional(propagation = Propagation.REQUIRED)
	public void addMessageSend(String merinfoNo, String phone) throws ServiceException {
		 
		try {
			//您已开通付临门收单运营平台，您的账号：XXX，您的密码是：XXX，系统的链接地址为：XXXX
			StringBuffer sb = new StringBuffer();
			String mesContent = sb.append("您已开通付临门收单运营平台，您的账号：")
					.append(merinfoNo)
					.append("，您的密码是：")
					.append(phone.substring(5))
					.append("，系统的链接地址为：https://shoudan.freemypay.com:18081/fmposm/login.jsp").toString();
			logger.info("保存发送短信内容："+mesContent);
			MessageSend ms = new MessageSend();
			ms.setPhoneNumber(phone);
			ms.setMesContent(mesContent);
			ms.setSendFlag("0");
			ms.setDtCreate(new Date());
			ms.setTimes(0);
			userDao.editSave(ms);
			logger.info("-------商户["+merinfoNo+"]开通添加短信表成功----");
		} catch (Exception e) {
			logger.error("添加商户到操作员失败",e);
			throw new ServiceException("添加商户到操作员失败",e);
		}
	}

	@Transactional(readOnly=true)
	public String queryAreaDetailBy32Code(String param) throws ServiceException {
		String result="";
		try {
			if(null==param)return null;
			String unCode=param.substring(4);
			String hql="FROM TblDictionaryLayerItem t  where t.id.dicType='UnionPay_Area' and t.id.dicCode=?";
			Object[] obj={unCode};
			List<?> objList=userDao.queryAll(hql, obj);
			if(null != objList && objList.size()>0){
				int i=0;
				if(objList.size()>1){
					Iterator<?> itor=objList.iterator();
					while (itor.hasNext()) {
						TblDictionaryLayerItem td=(TblDictionaryLayerItem)itor.next();
						String name=td.getName();
						int index=name.indexOf("_");
						if(index>0){
							name=name.substring(index+1);
						}		
						if(i==0){
							result=result+name;
						}else{
							result=result+" - "+name;
						}
						i++;
					}
				}else{
					TblDictionaryLayerItem td=(TblDictionaryLayerItem)objList.get(0);
					Object[] obj1={td.getId().getDicPcode()};
					if(Long.parseLong(td.getId().getDicLevel())==1){
						result=td.getName();
					}else if(Long.parseLong(td.getId().getDicLevel())==2){
						String hql1="Select t.name FROM TblDictionaryLayerItem t  "
								  + "where t.id.dicType='UnionPay_Area' and t.id.dicCode=? and t.id.dicLevel=1";
						
						String firstName=(String)userDao.createQueryUniqueResult(hql1, obj1);
						result=firstName+" - "+td.getName();
					}else{
						StringBuffer sb= new StringBuffer();
						sb.append("SELECT * FROM (")
						.append(" SELECT T.NAME, T.DIC_LEVEL  FROM TBL_DICTIONARYLAYERITEM T ")
						.append(" WHERE T.DIC_TYPE = 'UnionPay_Area' AND T.DIC_CODE =? AND T.DIC_LEVEL = 2 ")
						.append(" UNION")
						.append(" SELECT T.NAME, T.DIC_LEVEL FROM TBL_DICTIONARYLAYERITEM T ")
						.append(" WHERE T.DIC_TYPE = 'UnionPay_Area' AND T.DIC_CODE = (SELECT T.DIC_PCODE  FROM TBL_DICTIONARYLAYERITEM T")
							.append(" WHERE T.DIC_TYPE = 'UnionPay_Area'   AND T.DIC_CODE = ?  AND T.DIC_LEVEL = 2)")
						.append(" AND T.DIC_LEVEL = 1) TBL ORDER BY DIC_LEVEL ASC");
						Object[] obj2={td.getId().getDicPcode(),td.getId().getDicPcode()};
						List<?> objList1=sqlBaseDao.queryAll(sb.toString(), obj2);
						if(null!=objList1 && objList1.size()>0){
							Iterator<?> itor =objList1.iterator();
							while(itor.hasNext()){
								Object[] object=(Object[])itor.next();
								String name=object[0]+"";
								int index=name.indexOf("_");
								if(index>0){
									name=name.substring(index+1);
								}		
								if(i==0){
									result=result+name;
								}else{
									result=result+" - "+name;
								}
								i++;
							}
							result=result+" - "+td.getName().substring(td.getName().indexOf("_")+1);;
						}
					}
				}
			}
			return result;
		} catch (Exception e) {
			logger.error("查询32域所属地区信息失败",e);
			throw new ServiceException("查询32域所属地区信息失败",e);
		}
	}

	@Override
	public boolean isCheckMerinfo() throws ServiceException {
		String sql="SELECT COUNT(1) FROM T_OPERATORS T  WHERE T.ACCOUNT_NO = 'cj'  AND T.QQ = '1' ";
		try {
			Object obj= pageDao.findObj(sql, null);
			if(null!=obj ){
				if( Long.parseLong(obj.toString())>0){
					return true;
				}else{
					return false;
				}
			}
		} catch (DaoException e) {
			logger.error("---查询账号[cj]的批量审核状态失败----",e);
			throw new  ServiceException("查询账号[cj]的批量审核状态失败",e);
		}
		return false;
	}

	@Transactional(rollbackFor = { ServiceException.class })
	public String editOperStatus() throws ServiceException {
		String sql="UPDATE T_OPERATORS T SET T.QQ=?  WHERE T.ACCOUNT_NO = 'cj'";
		try {
			
			String status="";
			boolean isClose=isCheckMerinfo();
			if(isClose==false){ //关闭
				status="1";
				 
			}else{
				status="0";
				 
			}
			List<Object> objList=new ArrayList<Object>();
			objList.add(status);
			int j=sqlBaseDao.deleteBySql(sql, objList);
			if(j>0){
				return status+"_0";
			}
		} catch (DaoException e) {
			logger.error("---更新账号[cj]的批量审核状态失败----",e);
			throw new  ServiceException("更新账号[cj]的批量审核状态失败",e);
		}
		return "";
	}
	
	
	   @Transactional(rollbackFor = { ServiceException.class })
	   public void insertLoginInfo(LoginIpJnls loginInfo) throws ServiceException {
	       try {
	    	   userDao.editSave(loginInfo);
              } catch (DaoException e) {
                  logger.error("保存登录信息失败", e);
                  throw new ServiceException("保存登录信息失败");
              }
	    }
}
